﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Office = Microsoft.Office.DocumentManagement.DocumentSets;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;
using System.Collections;
using MS.InformationManagement.DAL.DocumentCenter;
using System.IO;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.Support.Enums;
using MS.InformationManagement.Core.RecordSiteQuery;
using MS.InformationManagement.DAL.RecordCenter;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.FileCreator;
using DocumentFormat.OpenXml.Wordprocessing;
using MS.InformationManagement.Core.IncommingDocuments;
using MS.InformationManagement.Core.TransactionsResponse;
using DAL = MS.InformationManagement.DAL.DTOs;
using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint.Utilities;



namespace MS.InformationManagement.Core.Documentset
{
    public abstract class BaseDocumentSet<R> : IRadicado where R : Radicado
    {

        #region fields

        SPWeb _currentWeb;

        #endregion

        #region Properties

        public R CurrentRadicado;
        public string CurrentLibrary;
        public string InitialAssidnedUser;
        public Office.DocumentSet CurrentDocumentSet { get; set; }
        public string TargetLibrary
        {
            get
            {
                return string.IsNullOrEmpty(CurrentLibrary) ? SPContext.Current.List.Title : CurrentLibrary;
            }
        }
        public SPWeb CurrentWeb
        {
            get { return _currentWeb == null ? SPContext.Current.Web : _currentWeb; }
            set { _currentWeb = value; }
        }
        public string CurrentContentType;

        #endregion

        #region Constructors

        public BaseDocumentSet(R radicado) { CurrentRadicado = radicado; }

        public BaseDocumentSet() { }

        #endregion

        #region Implemented Methods

        public virtual string NewRadicado(SPFolder parentFolder)
        {
            this.CreateDocument(parentFolder, this.CurrentContentType);
            this.CurrentDocumentSet.Folder.Item.Update();
            this.updateMetadata();
            return this.CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString();
        }

        public void CreateDocument(SPFolder parentFolder, string contentType)
        {
            string tempName = Guid.NewGuid().ToString();
            SPFolder newDocument = parentFolder.SubFolders.Add(tempName);
            newDocument.Item[SPBuiltInFieldId.ContentType] = contentType;
            InitialAssidnedUser = parentFolder.Item[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED].ToString();
            newDocument.Item.Update();
            newDocument.Update();
            CurrentDocumentSet = Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(newDocument);
            CurrentDocumentSet.Log(string.Empty, DateTime.Now, TraceableOperation.Radicado, SPContext.Current.Web.CurrentUser.LoginName, string.Empty);
            this.UpdateDocument();
        }

        public void CreateDocument(SPFolder parentFolder, string contentTypeName, Hashtable requiredFields)
        {
            //Creating new document
            string tempName = Guid.NewGuid().ToString();
            InitialAssidnedUser = parentFolder.Item[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED].ToString();
            SPContentTypeId contentTypeId = parentFolder.DocumentLibrary.ContentTypes[contentTypeName].Id;
            CurrentDocumentSet = Office.DocumentSet.Create(parentFolder.DocumentLibrary.RootFolder, tempName, contentTypeId, requiredFields);
            //CurrentDocumentSet.Log(string.Empty, DateTime.Now, TraceableOperation.Radicado, SPContext.Current.Web.CurrentUser.LoginName, string.Empty);
            this.UpdateDocument();

            //Moving new documento to expediente
            CurrentDocumentSet = Office.DocumentSet.GetDocumentSet(parentFolder.DocumentLibrary.GetItemById(CurrentDocumentSet.Item.ID).Folder);
            CurrentDocumentSet.Folder.MoveTo(parentFolder.Url + "/" + CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString());
        }


        /// <summary>
        /// Create a new radicado
        /// </summary>
        /// <param name="targetUserLoginName">User domian account domain\username or department</param>
        /// <param name="contentTypeName">Kind for the radicado to be created</param>
        /// <param name="radicadoName">Title for the radicado</param> 


        /// <summary>
        /// Create a new radicado
        /// </summary>
        /// <param name="targetUserLoginName">User domian account domain\username or department</param>
        /// <param name="contentTypeName">Kind for the radicado to be created</param>
        /// <param name="radicadoName">Title for the radicado</param>
        /// <param name="requiredStartingProperties">Required properties in order for documentID provider to work</param>
        public virtual void CreateDocument(string target, string contentTypeName, string radicadoName, Hashtable requiredStartingProperties)
        {
            InitialAssidnedUser = RadicadosHelper.GetUserSeccionEnchargedIfExists(target);
            SPList userList = null;
            string libraryName = string.Empty;
            if (string.IsNullOrEmpty(InitialAssidnedUser))
            {
                InitialAssidnedUser = target;
                libraryName = this.GetTargetLibrary(target);
            }
            else
                libraryName = InitialAssidnedUser.GetUserWithOutDomain();

            CurrentLibrary = libraryName;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(this.CurrentWeb.Url))
                {
                    using (SPWeb miWeb = site.OpenWeb())
                    {
                        miWeb.AllowUnsafeUpdates = true;
                        userList = miWeb.Lists.TryGetList(libraryName);
                        if (userList == null)
                            throw new Exception(string.Format(ExceptionConstants.ERROR_BIBLIOTECA_USUARIO_INEXISTENTE, libraryName));
                        SPDocumentLibrary userLibrary = userList as SPDocumentLibrary;
                        SPContentTypeId contentType = userLibrary.ContentTypes[contentTypeName].Id;
                        string tempName = Guid.NewGuid().ToString();
                        CurrentDocumentSet = Office.DocumentSet.Create(userLibrary.RootFolder, tempName, contentType, requiredStartingProperties);
                        CurrentDocumentSet.Log(string.Empty, DateTime.Now, TraceableOperation.Radicado, CurrentRadicado.Radicador, string.Empty);
                        miWeb.AllowUnsafeUpdates = false;
                    }
                }
            });


            this.UpdateDocument();
        }

        public virtual void UpdateDocument()
        {
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_NAME] = CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString();
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_DESCRIPCION] = CurrentRadicado.Name;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_RADICADOR] = CurrentRadicado.Radicador;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED] = InitialAssidnedUser;
            CurrentDocumentSet.Folder.Item.Update();
            CurrentDocumentSet.Folder.Update();
        }

        /// <summary>
        /// Create a new log entry in the document set, its necessary to call folder.item.update after call this method
        /// </summary>
        public void LogUpdate()
        {
            DateTime currentDate = DateTime.Now;
            CurrentDocumentSet.Log(string.Empty, currentDate, TraceableOperation.Actualizado, SPContext.Current.Web.CurrentUser.Name, string.Empty);
            //TryLogTRDChange(currentDate);
        }


        public bool TryLogTRDChange(DateTime dateTime)
        {

            bool edited = false;

            if (CurrentRadicado.IDSubSeccion.HasValue &&
                (CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_SUBSECCION] != null &&
                !CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_SUBSECCION].Equals(CurrentRadicado.IDSubSeccion.Value)))
            {
                Seccion selectedSubsection = QueryRecordsSiteHelper<Seccion>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_SECCION, Convert.ToInt32(CurrentRadicado.IDSubSeccion.Value));

                if (selectedSubsection != null)
                {
                    CurrentDocumentSet.Log(string.Empty, dateTime, TraceableOperation.Actualizado, SPContext.Current.Web.CurrentUser.Name, string.Format("Asignación de tabla de retención documental, subseccion {0}", selectedSubsection.Title));
                    edited = true;
                }
                else
                {
                    CurrentDocumentSet.Log(string.Empty, dateTime, TraceableOperation.Actualizado, SPContext.Current.Web.CurrentUser.Name, "Asignación de tabla de retención documental, eliminando tipificacion de la subsección");
                    edited = true;
                }
            }
            else if (CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_SUBSECCION] == null && CurrentRadicado.IDSubSeccion.HasValue && CurrentRadicado.IDSubSeccion.Value != 0)
            {
                Seccion selectedSubsection = QueryRecordsSiteHelper<Seccion>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_SECCION, Convert.ToInt32(CurrentRadicado.IDSubSeccion.Value));
                CurrentDocumentSet.Log(string.Empty, dateTime, TraceableOperation.Actualizado, SPContext.Current.Web.CurrentUser.Name, string.Format("Asignación de tabla de retención documental, subseccion {0}", selectedSubsection.Title));
                edited = true;
            }

            if (CurrentRadicado.IDTRD.HasValue &&
                (CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_TRD] != null &&
                !CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_TRD].Equals(CurrentRadicado.IDTRD.Value)))
            {
                Subserie selectedSubSerie = QueryRecordsSiteHelper<Subserie>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_SUBSERIE, Convert.ToInt32(CurrentRadicado.IDTRD.Value));
                if (selectedSubSerie != null)
                {
                    CurrentDocumentSet.Log(string.Empty, dateTime, TraceableOperation.Actualizado, SPContext.Current.Web.CurrentUser.Name, string.Format("Asignación de tabla de retención documental, subserie {0}", selectedSubSerie.Title));
                    edited = true;
                }
                else
                {
                    CurrentDocumentSet.Log(string.Empty, dateTime, TraceableOperation.Actualizado, SPContext.Current.Web.CurrentUser.Name, "Asignación de tabla de retención documental, eliminando tipificacion de la subserie");
                    edited = true;
                }
            }
            else if (CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_TRD] == null && CurrentRadicado.IDTRD.HasValue && CurrentRadicado.IDTRD.Value != 0)
            {
                Subserie selectedSubSerie =
                    QueryRecordsSiteHelper<Subserie>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_SUBSERIE, Convert.ToInt32(CurrentRadicado.IDTRD.Value));
                CurrentDocumentSet.Log(string.Empty, dateTime, TraceableOperation.Actualizado, SPContext.Current.Web.CurrentUser.Name, string.Format("Asignación de tabla de retención documental, subserie {0}", selectedSubSerie.Title));
                edited = true;
            }

            if (CurrentRadicado.Document_Documental_Type_ID.HasValue &&
                (CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_DCOUMENTAL_TYPE_ID] != null &&
                !CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_DCOUMENTAL_TYPE_ID].Equals(Convert.ToDouble(CurrentRadicado.Document_Documental_Type_ID.Value))))
            {
                TipoDocumental selectedDocumentalType =
                    QueryRecordsSiteHelper<TipoDocumental>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_TIPOS_DOCUMENTALES, CurrentRadicado.Document_Documental_Type_ID.Value);
                if (selectedDocumentalType != null && selectedDocumentalType != default(TipoDocumental))
                {
                    CurrentDocumentSet.Log(string.Empty, dateTime, TraceableOperation.Actualizado, SPContext.Current.Web.CurrentUser.Name, string.Format("Asignación de tabla de retención documental, tipo de documento {0}", selectedDocumentalType.Title));
                    edited = true;
                }
                else
                {
                    CurrentDocumentSet.Log(string.Empty, dateTime, TraceableOperation.Actualizado, SPContext.Current.Web.CurrentUser.Name, "Asignación de tabla de retención documental, eliminando tipificación de tipo de documento");
                    edited = true;
                }
            }
            else if (CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_DCOUMENTAL_TYPE_ID] == null && CurrentRadicado.Document_Documental_Type_ID.HasValue && CurrentRadicado.Document_Documental_Type_ID != 0)
            {
                TipoDocumental selectedDocumentalType =
                QueryRecordsSiteHelper<TipoDocumental>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_TIPOS_DOCUMENTALES, CurrentRadicado.Document_Documental_Type_ID.Value);

                CurrentDocumentSet.Log(string.Empty, dateTime, TraceableOperation.Actualizado, SPContext.Current.Web.CurrentUser.Name, string.Format("Asignación de tabla de retención documental, tipo de documento {0}", selectedDocumentalType.Title));
                edited = true;
            }

            return edited;
        }
        /// <summary>
        /// Load files to current documentset
        /// </summary>
        public void LoadFilesToDocumentSet()
        {
            Office.DocumentSet updatedDocSet = GetDocumentSet(this.CurrentDocumentSet.Item.ID);
            if (updatedDocSet.Folder.Files.Count > 0) return;
            foreach (var file in this.CurrentRadicado.AttachedFiles)
            {
                SPFile newFile = null;

                Hashtable fileProperties = new Hashtable();
                fileProperties.Add(CustomSiteColumns.FIELD_DOCUMENT_IS_MAIN, file.IsMainDocument);

                if (file.IsMainDocument)
                {
                    string id = updatedDocSet.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID] + "";
                    Hashtable Content = new Hashtable();
                    Content.Add(GlobalConstants.ETIQUETA_ID_RADICADO, new FileCreator { Text = id, FontName = fontName.Arial, FontSize = 20, HorizontallyAlign = JustificationValues.Right, isBold = true });
                    Content.Add(GlobalConstants.ETIQUETA_FECHA_SYSTEMA, new FileCreator { Text = DateTime.Now.ToShortDateString() + " Hora " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + "s", FontName = fontName.Arial, FontSize = 20, HorizontallyAlign = JustificationValues.Right, isBold = true });
                    Content.Add(GlobalConstants.ETIQUETA_CON_COPIA, new FileCreator { Text = ReturnConCopia(this.CurrentRadicado.AttachedCopys), FontName = fontName.Arial, FontSize = 17, HorizontallyAlign = JustificationValues.Left, isBold = false });
                    if (CurrentRadicado is RadicadoBaseSalida )
                        newFile = MS.InformationManagement.Support.OfficeWordHelper.RemplazarWordFromTemplate(file.FileContent, Content, updatedDocSet, file.FileName, true);
                    else
                        newFile = updatedDocSet.Folder.Files.Add(file.FileName, file.FileContent, fileProperties, true);
                }
                else
                    newFile = updatedDocSet.Folder.Files.Add(file.FileName, file.FileContent, fileProperties, true);


                newFile.Item[SPBuiltInFieldId.ContentType] = GlobalConstants.CTTN_ARCHIVE;
                newFile.Item.Update();
            }
            updatedDocSet.Folder.Update();
        }


        /// <summary>
        /// Load files to current documentset
        /// </summary>
        public void LoadCopysToDocumentSet()
        {
            Office.DocumentSet updatedDocSet = GetDocumentSet(this.CurrentDocumentSet.Item.ID);
            foreach (var copy in this.CurrentRadicado.AttachedCopys)
            {
                UTF8Encoding encoding = new System.Text.UTF8Encoding();
                byte[] content = encoding.GetBytes(string.Empty);


                SPFile newFile = updatedDocSet.Folder.Files.Add(Guid.NewGuid().ToString(), content);
                newFile.Update();
                newFile.Item[SPBuiltInFieldId.ContentType] = GlobalConstants.CTTN_COPIAS_RADICADO;
                newFile.Item[CustomSiteColumns.FLD_COPY_CONTACT_ID] = copy.Id;
                newFile.Item[CustomSiteColumns.FLD_COPY_CONTACT_ADDRESS] = copy.Direccion;
                newFile.Item[CustomSiteColumns.FLD_COPY_CONTACT_PHONE] = copy.Telefono;
                newFile.Item[CustomSiteColumns.FLD_COPY_CONTACT_EMAIL] = copy.Email;
                newFile.Item[CustomSiteColumns.FLD_COPY_ENVIO_ID] = copy.IdMedioEnvio;
                newFile.Item[CustomSiteColumns.FLD_COPY_ENVIO_NAME] = copy.MedioEnvio;
                newFile.Item[CustomSiteColumns.FLD_COPY_NAME] = copy.Nombre;
                newFile.Item[CustomSiteColumns.FLD_COPY_REPRESENTANTE] = copy.Representante;
                newFile.Item.Update();

            }
            updatedDocSet.Folder.Update();
        }

        /// <summary>
        /// Load files to current documentset
        /// </summary>
        public void UpdateCopysToDocumentSet(List<int> CurrentCopys)
        {
            for (int i = 0; i < CurrentCopys.Count(); i++)
            {
                SPList currentList = this.CurrentDocumentSet.ParentList;
                var OldCopy = this.CurrentRadicado.AttachedCopys.Where(x => x.IdItem == CurrentCopys[i]).FirstOrDefault();
                SPListItem itemToUpdate = currentList.GetItemById(CurrentCopys[i]);
                itemToUpdate[CustomSiteColumns.FLD_COPY_CONTACT_ID] = OldCopy.Id;
                itemToUpdate[CustomSiteColumns.FLD_COPY_CONTACT_ADDRESS] = OldCopy.Direccion;
                itemToUpdate[CustomSiteColumns.FLD_COPY_CONTACT_PHONE] = OldCopy.Telefono;
                itemToUpdate[CustomSiteColumns.FLD_COPY_CONTACT_EMAIL] = OldCopy.Email;
                itemToUpdate[CustomSiteColumns.FLD_COPY_ENVIO_ID] = OldCopy.IdMedioEnvio;
                itemToUpdate[CustomSiteColumns.FLD_COPY_ENVIO_NAME] = OldCopy.MedioEnvio;
                itemToUpdate[CustomSiteColumns.FLD_COPY_NAME] = OldCopy.Nombre;
                itemToUpdate[CustomSiteColumns.FLD_COPY_REPRESENTANTE] = OldCopy.Representante;
                itemToUpdate.Update();
            }
        }

        /// <summary>
        /// Get a document set object for the current document set library
        /// </summary>
        /// <param name="id">Id for the document set</param>
        /// <returns>Radicado object</returns>
        public virtual R GetRadicado(int id)
        {
            R radicado = default(R);

            using (DCDocumentCenterDataContext dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                radicado = (from radInterno in dc.GetList<R>(TargetLibrary).ScopeToFolder("", true) //Insert folder name if application presents performance issues
                            where radInterno.Id == id
                            select radInterno).FirstOrDefault();
                if (radicado == null) return null;
                Office.DocumentSet currentDoc = GetDocumentSet(id);

                radicado.AttachedFiles = (from file in currentDoc.Folder.Files.OfType<SPFile>()
                                          where file.Item.ContentType.Name != GlobalConstants.CTTN_COPIAS_RADICADO
                                          select new FileEntity
                                          {
                                              CreationDate = SPUtility.ParseDate(SPContext.Current.Web, file.Item[SPBuiltInFieldId.Created].ToString(), SPDateFormat.DateTime, false),
                                              FileContent = file.OpenBinary(),
                                              FileName = file.Name,
                                              FileSize = file.OpenBinary().Length / 1024,
                                              IsMainDocument = ListHelper.ConvertToBoolean(file.Item[CustomSiteColumns.FIELD_DOCUMENT_IS_MAIN] + "")
                                          }).ToList();

                radicado.AttachedCopys = (from file in currentDoc.Folder.Files.OfType<SPFile>()
                                          where file.Item.ContentType.Name == GlobalConstants.CTTN_COPIAS_RADICADO
                                          select new DAL.DTOs.ContactsDTO
                                          {
                                              IdItem = file.Item.ID,
                                              Id = file.Item[CustomSiteColumns.FLD_COPY_CONTACT_ID] + "",
                                              Direccion = file.Item[CustomSiteColumns.FLD_COPY_CONTACT_ADDRESS] + "",
                                              Telefono = file.Item[CustomSiteColumns.FLD_COPY_CONTACT_PHONE] + "",
                                              Email = file.Item[CustomSiteColumns.FLD_COPY_CONTACT_EMAIL] + "",
                                              IdMedioEnvio = file.Item[CustomSiteColumns.FLD_COPY_ENVIO_ID] + "",
                                              MedioEnvio = file.Item[CustomSiteColumns.FLD_COPY_ENVIO_NAME] + "",
                                              Nombre = file.Item[CustomSiteColumns.FLD_COPY_NAME] + "",
                                              Representante = file.Item[CustomSiteColumns.FLD_COPY_REPRESENTANTE] + ""
                                          }).ToList();
                radicado.LogEntries = currentDoc.GetLog();
                radicado.DeliveryLogs = currentDoc.GetDeliveryLog();
            }

            return radicado;
        }

        /// <summary>
        /// Get document set object for current library
        /// </summary>
        /// <param name="id">Documentset id</param>
        /// <returns>Document Set object</returns>
        public Office.DocumentSet GetDocumentSet(int id)
        {
            SPList currentListObject = this.CurrentDocumentSet == null ? SPContext.Current.Web.Lists[TargetLibrary] : this.CurrentDocumentSet.ParentList;
            var spFolder = currentListObject.GetItemById(id).Folder;
            return Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(spFolder);
        }

        /// <summary>
        /// Get document set object for current library
        /// </summary>
        /// <param name="id">Documentset id</param>
        /// <returns>Document Set object</returns>
        public Office.DocumentSet GetDocumentSet(int id, SPWeb web)
        {
            SPList currentListObject = this.CurrentDocumentSet == null ? web.Lists.TryGetList(TargetLibrary) : this.CurrentDocumentSet.ParentList;
            var spFolder = currentListObject.GetItemById(id).Folder;
            return Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(spFolder);
        }

        /// <summary>
        /// Remove all files in documentset
        /// </summary>
        /// <param name="docSet"></param>
        public void RemoveFiles(Office.DocumentSet docSet)
        {
            Office.DocumentSet updatedDocSet = GetDocumentSet(docSet.Item.ID);
            while (docSet.Folder.Files.Count > 0)
            {
                updatedDocSet.Folder.Files.Delete(docSet.Folder.Files[docSet.Folder.Files.Count - 1].Url);
            }
            updatedDocSet.Folder.Update();
        }

        public static Office.DocumentSet GetDocumentSet(SPList list, int id)
        {
            var spFolder = list.GetItemById(id).Folder;
            var documentSet = Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(spFolder);
            return documentSet;
        }

        public static SPListItemCollection getChildsFromDocumentSet(SPList list, string RadicadoID)
        {
            SPQuery query = new SPQuery();
            query.Query = string.Format("<Where><Eq><FieldRef Name='" + CustomSiteColumns.FIELD_DOCUMENT_RADICADO_PADRE + "'/><Value Type='Text'>{0}</Value></Eq></Where>", RadicadoID);
            var documents = list.GetItems(query);
            return documents;
        }

        #endregion

        #region Declared Methods

        public abstract ITransactionResponse NewRadicado();
        public abstract void UpdateRadicado();
        public abstract string GetTargetLibrary(string target);
        public abstract void updateMetadata();

        #endregion

        #region Private Methods

        public DateTime? getDaysForResponse()
        {
            Subserie selectedSerie = QueryRecordsSiteHelper<Subserie>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_SUBSERIE, int.Parse(CurrentRadicado.IDTRD.Value.ToString()));
            DateTime DayForResponse = DateTime.Now;

            if (!selectedSerie.TiempoDeRespuesta.HasValue)
                return null;
            else
            {
                for (int i = 0; i < selectedSerie.TiempoDeRespuesta.Value; i++)
                {
                    DayForResponse = BusinessDateHelper.GetNextBusinessDay(DayForResponse);
                }
                return DayForResponse;
            }
        }

        protected void AddIncommingRadicado()
        {
            AddIncommingDocumentAction incommingRadicado = new AddIncommingDocumentAction(this.CurrentDocumentSet);
            incommingRadicado.Execute();
        }

        private string ReturnConCopia(List<DAL.DTOs.ContactsDTO> copias)
        {
            string copiasTxt = string.Empty;
            if (copias != null)
            {
                foreach (DAL.DTOs.ContactsDTO cc in copias)
                {
                    if (string.IsNullOrEmpty(cc.Representante))
                        copiasTxt += cc.Nombre + " / ";
                    else
                        copiasTxt += cc.Nombre + " - " + cc.Representante + " / ";
                }
            }
            return copiasTxt;
        }

        protected void CreateRadicadoDistribucion(string userAssigned, string idRadicado, string folios, string anexos)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ElevatedsiteColl = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb())
                    {

                        ElevatedsiteColl.AllowUnsafeUpdates = true;
                        ElevatedSite.AllowUnsafeUpdates = true;
                        SPList targetList = null;
                        targetList = ElevatedSite.Lists.TryGetList("Distribucion");
                        SPContext.Current.Web.AllowUnsafeUpdates = true;
                        SPListItem item = targetList.AddItem();
                        item[CustomSiteColumns.FIELD_DOCSET_ID_RADICADO] = idRadicado.ToUpper();
                        item[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED] = userAssigned;
                        item[CustomSiteColumns.FIELD_DOCSET_INTERNAL_RECEPTION] = false;
                        item[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS] = Convert.ToDouble(folios);
                        item[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS_ANEX] = Convert.ToDouble(anexos);
                        item.Update();
                        ElevatedsiteColl.AllowUnsafeUpdates = false;
                        ElevatedSite.AllowUnsafeUpdates = false;
                    }
                }
            });
        }

        #endregion

    }
}
